<template>
  <div class="main-container">
    <div class="content-card">
      <!-- 搜索-->
      <div style="margin-bottom: 20px;">
        <el-form inline="true" size="default">
          <el-form-item label="订单编号" >
            <el-input v-model="search1" placeholder="请输入订单编号"  clearable>
              <template #prefix><el-icon class="el-input__icon"><search/></el-icon></template>
            </el-input>
          </el-form-item >
          <el-form-item label="订单状态" >
             <el-select v-model="search2" placeholder="请选择状态" clearable>
                <el-option label="已创建" value="已创建"></el-option>
                <el-option label="已支付" value="已支付"></el-option>
                <el-option label="已发货" value="已发货"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已取消" value="已取消"></el-option>
             </el-select>
          </el-form-item >
          <el-form-item>
            <el-button type="primary" @click="load">
              <el-icon style="margin-right: 5px"><search/></el-icon>查询
            </el-button>
            <el-button @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据字段-->
      <el-table :data="tableData" stripe style="width: 100%" :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
        <el-table-column prop="orderNo" label="订单编号" sortable />
        <el-table-column prop="totalPrice" label="总金额" sortable>
          <template #default="scope">
            ¥{{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" sortable/>
        <el-table-column prop="status" label="状态" >
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == '已创建'" type="info" effect="plain">已创建</el-tag>
            <el-tag v-else-if="scope.row.status == '已支付'" type="primary" effect="plain">已支付</el-tag>
            <el-tag v-else-if="scope.row.status == '已发货'" type="warning" effect="plain">已发货</el-tag>
            <el-tag v-else-if="scope.row.status == '已完成'" type="success" effect="plain">已完成</el-tag>
            <el-tag v-else type="danger" effect="plain">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <div style="display: flex; align-items: center; gap: 10px;">
              <!-- Admin Actions -->
              <template v-if="user.role == 1">
                 <el-button size="small" type="primary" link @click="updateStatus(scope.row, '已发货')" v-if="scope.row.status == '已支付'">发货</el-button>
                 <el-button size="small" type="danger" link @click="updateStatus(scope.row, '已取消')" v-if="scope.row.status != '已完成' && scope.row.status != '已取消'">取消订单</el-button>
              </template>
              <!-- User Actions -->
              <template v-if="user.role == 2">
                 <el-button size="small" type="success" link @click="updateStatus(scope.row, '已支付')" v-if="scope.row.status == '已创建'">支付</el-button>
                 <el-button size="small" type="primary" link @click="updateStatus(scope.row, '已完成')" v-if="scope.row.status == '已发货'">确认收货</el-button>
                 <el-button size="small" type="danger" link @click="updateStatus(scope.row, '已取消')" v-if="scope.row.status == '已创建'">取消订单</el-button>
              </template>
              <el-button size="small" link @click="viewDetails(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--    分页-->
      <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
            v-model:currentPage="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        >
        </el-pagination>
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailsVisible" title="订单详情" width="50%">
        <el-table :data="currentDetails" border :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
            <el-table-column prop="bookName" label="书名"></el-table-column>
            <el-table-column prop="isbn" label="ISBN"></el-table-column>
            <el-table-column prop="price" label="单价">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="detailsVisible = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>
  </div>

</template>

<script>
import request from "../utils/request";
import {ElMessage} from "element-plus";

export default {
  name: 'Order',
  created(){
    let userStr = sessionStorage.getItem("user") ||"{}"
    this.user = JSON.parse(userStr)
    this.load()
  },
  methods: {
    load(){
      request.get("/order",{
        params:{
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          orderNo: this.search1,
          status: this.search2,
          userId: this.user.role == 2 ? this.user.id : null // Admin sees all, User sees own
        }
      }).then(res =>{
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    clear(){
      this.search1 = ""
      this.search2 = ""
      this.load()
    },
    updateStatus(row, status){
        let updatedRow = { ...row, status: status };
        request.put("/order", updatedRow).then(res => {
            if(res.code == 0){
                ElMessage.success("操作成功");
                this.load();
            } else {
                ElMessage.error(res.msg);
            }
        });
    },
    viewDetails(row){
        request.get("/order/" + row.id).then(res => {
             if(res.code == '0'){
                 this.currentDetails = res.data.details;
                 this.detailsVisible = true;
             } else {
                 ElMessage.error(res.msg);
             }
        });
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum){
      this.currentPage = pageNum
      this.load()
    }
  },
  data() {
    return {
      search1:'',
      search2:'',
      total:10,
      currentPage:1,
      pageSize: 10,
      tableData: [],
      user:{},
      detailsVisible: false,
      currentDetails: []
    }
  },
}
</script>